package cn.cloudplug.core.net;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.cloudplug.core.index.ConfigKeys;
import cn.cloudplug.core.index.Scent;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by pc on 2018/1/18.
 */

public class RestCreator {

    /**
     * 构建OkHttp
     */
    private static final class OKHttpHolder {
        private static final long TIME_OUT = 60;
        private static final OkHttpClient.Builder BUILDER = OkHttpClientBuilderInit();
        private static final OkHttpClient OK_HTTP_CLIENT = BUILDER
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();

        private static OkHttpClient.Builder OkHttpClientBuilderInit() {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            List<Interceptor> interceptors = Scent.getConfiguration(ConfigKeys.Interceptor);
            if(interceptors!=null)
            for (Interceptor interceptor : interceptors) {
                builder.addInterceptor(interceptor);
            }
            return builder;
        }
    }

    /**
     * 构建全局Retrofit客户端
     */
    private static final class RetrofitHolder{
        private static final String BASE_URL = Scent.getConfiguration(ConfigKeys.BaseUrl);
        private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(OKHttpHolder.OK_HTTP_CLIENT)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
    }

    /**
     * Service接口
     */
    private static final class RestServiceHolder {
        private static final RestService REST_SERVICE = create(RestService.class);
    }

    public static RestService getRestService(){
        return RestServiceHolder.REST_SERVICE;
    }

    public static <T> T create(Class<T> tClass){
        return RetrofitHolder.RETROFIT_CLIENT.create(tClass);
    }
}
